• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
musafir2007

simple char array, please help

16 posts in this topic

Hi, I am trying to simple return a string but I get this error:

In function 'getNetworkAtPriority':

warning: function returns address of local variable
In function 'main':
error: incompatible types in assignment

 

Please help what I am doing wrong? thanks

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * getNetworkAtPriority( )
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}

int main()
{
    char entry1[14];
    entry1 = getNetworkAtPriority( "1" );

    return 0;
}
Edited by musafir2007
1

Share this post


Link to post
Share on other sites
For the first warning, when you try to return an array, what you're actually doing is returning a pointer to the first element of the array. In your code, you allocate the array as a local variable meaning that it gets destroyed when you leave the function. This means that the pointer you return is pointing to garbage. If you're using C++ you can use the std::string class instead of a char * as a return type. If you're using plain C then you have the choice of either passing the address of a buffer that the function will fill with the string data or dynamically allocating the buffer to be returned. For instance you can allocate a buffer with malloc() before the sprintf() call or use strdup() on the buffer after the sprintf() call to return a duplicate of the string.

For the error, you are trying to use assignment on a pointer to an array. This isn't legal C or C++. In C++ if you use std::string instead of a char array for entry1 you can use assignment. In C you can use strcpy() or a similar copy function to copy the contents of the returned string to your buffer.
2

Share this post


Link to post
Share on other sites

As SiCrane stated, your buffer will get invalid (out of scope) once the function return. It might work, and it might not... Use something like this instead:

void getNetworkAtPriority(char *firstArgument, char *pBuf)
{
    sprintf(pBuf, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    ZeroMemory(&entry1[0], 14);

    getNetworkAtPriority("1", &entry1[0]);

    return 0;
}


 
Guard that against buffer overrun!
 
When you supply a buffer pointer to a function you should always provide the length of the buffer as well, and ensure that the function does not write beyond the end of the buffer.
 
int stuffToBuff(char* buffer, size_t bufferLength) {
  char thingToCopy[] = "Hello, world!";
  if(strlen(thingToCopy) >= bufferLength) {
    return -1; //indicate failure
  }
  strcpy(buffer, thingToCopy);
  return 0; //indicate success
}

int main() {
  char buf[20];
  int result = stuffToBuff(buf, 20);
  if(result == -1) {
    //there was an error!
  }
  return 0;
}
Remember that C-style strings require a zero at the end, so your buffer needs to be one longer than the number of characters being copied.
2

Share this post


Link to post
Share on other sites

Guard that against buffer overrun!
 [...]

Or even simpler:
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);

    return 0;
}
2

Share this post


Link to post
Share on other sites

Note that you can return a literal string from a function safely, a string literal lives for the entire duration of the program. However, you cannot modify the literal, so the return value should be marked "const", as would the variable which would receive this result.

 
const char *getNetworkAtPriority()
{
    return  "mcc-mnc-umts";
}

The only risk here is the function signature would have to change if you wanted to change the implementation to be more dynamic later.

2

Share this post


Link to post
Share on other sites

Thanks all!

what if I want to try this with global variable?

 

why [mod edit: are these] not working?

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
char* getNetworkAtPriority()
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}
 
int main()
{
    entry1 = getNetworkAtPriority( "1" );
    return 0;
}

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
char* getNetworkAtPriority()
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}
 
int main()
{
    strcpy(entry1, getNetworkAtPriority());
    printf("Return:%s", entry1);
    return 0;
}

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
void getNetworkAtPriority()
{
    sprintf( entry1, "mcc-mnc-umts");
    //return returnValue;
}
 
int main()
{
    //strcpy(entry1, getNetworkAtPriority());
    printf("Value:%s", entry1);
    return 0;
}
Edited by rip-off
mod edit: restoring defaced question
0

Share this post


Link to post
Share on other sites

As SiCrane said in the very first reply; you are returning a local array. As soon as the function getNetworkAtPriority returns, the array no longer exists. It doesn't matter that some other array is global or not, the array returnValue is destroyed and no longer exists at the time you try to use strcpy on it.

1

Share this post


Link to post
Share on other sites
I really like the following way of doing it, and it seems to work on new compiler,
But my c compiler doesn't seem to support snprintf. What alternative do i have?
Thanks!
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}
 
int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);
    printf("Return:%s", entry1);
    return 0;
}
Edited by musafir2007
0

Share this post


Link to post
Share on other sites

I really like the following way of doing it, and it seems to work on new compiler,
But my c compiler doesn't seem to support snprintf. What alternative do i have?
Thanks!
 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}
 
int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);
    printf("Return:%s", entry1);
    return 0;
}

Just use memcpy.

You should try to avoid the printf functions if you don't need the advanced formatting they provide.

True story, I once worked a at a bank, contracted to re-architect the code for the teller systems for an eventual port to Java ( which coincidentally never happened... Over a decade later, that same C++ code is running strong... ). Anyway in the process of modularizing a ton of code I happened to get into a low level logging function. Basically every single transaction was logged to the file system, so if there was fraud, a crash, whatever, they could play back each individual tellers transactions at the application level. Anyways there was a call to fprintf that always copied the same sized buffer ( a time stamp ) to a fixed sized string, I swapped out to use a straight memory copy instead...


Net effect? The entire application nearly doubled in speed. We were actually getting thank you emails from the branches over making such big improvements to the application,


Sorry, old many memory moment is now complete.
0

Share this post


Link to post
Share on other sites

Which compiler are you using? It may have snprintf(), but with a different spelling. Ex: MSVC calls it _snprintf().

0

Share this post


Link to post
Share on other sites

But my c compiler doesn't seem to support snprintf. What alternative do i have?

If you're using GCC/Clang, you can turn on C99 mode (default is C89, I believe). snprintf is part of the C99 standard, not the C89 standard. To turn on C99 mode with GCC or Clang, just pass the -std=c99 flag to the compiler when compiling. Or change your IDE to use C99 mode if you're using an IDE.

 

If you're using MSVC... it's a bit tricker, see below.
 
 

Just use memcpy.


You should try to avoid the printf functions if you don't need the advanced formatting they provide.

 a) Unless you have good reason to, don't worry about premature optimization. b) memcpy isn't necessarily a good replacement. I specifically used snprintf because it always null terminates the string. Always. memcpy does not, nor does strncpy. Yes, he can use memcpy, but he would have to 1) determine how long the source buffer is, 2) determine how long the dest buffer is, 3) pick the min of the two, 4) ensure the copied string is null terminated. It's certainly possible to use memcpy, but judging by his skill level, I think it's more worthwhile to suggest things that are less likely to lead him to screwing up (or at the very least, pointing out the caveats of alternative methods).
 

Which compiler are you using? It may have snprintf(), but with a different spelling. Ex: MSVC calls it _snprintf().

It should also be pointed out that there are a few gotchas if you use MSVC's _snprintf. Most notably, _snprintf does not necessarily null terminate the string (like snprintf always does). Additionally, the return values are different.  Before anyone uses _snprintf, they should first read this.

Edited by Cornstalks
0

Share this post


Link to post
Share on other sites

 

As SiCrane stated, your buffer will get invalid (out of scope) once the function return. It might work, and it might not... Use something like this instead:

void getNetworkAtPriority(char *firstArgument, char *pBuf)
{
    sprintf(pBuf, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    ZeroMemory(&entry1[0], 14);

    getNetworkAtPriority("1", &entry1[0]);

    return 0;
}


 
Guard that against buffer overrun!
 
When you supply a buffer pointer to a function you should always provide the length of the buffer as well, and ensure that the function does not write beyond the end of the buffer.
 
int stuffToBuff(char* buffer, size_t bufferLength) {
  char thingToCopy[] = "Hello, world!";
  if(strlen(thingToCopy) >= bufferLength) {
    return -1; //indicate failure
  }
  strcpy(buffer, thingToCopy);
  return 0; //indicate success
}

int main() {
  char buf[20];
  int result = stuffToBuff(buf, 20);
  if(result == -1) {
    //there was an error!
  }
  return 0;
}
Remember that C-style strings require a zero at the end, so your buffer needs to be one longer than the number of characters being copied.

 

 

Yea, i though about that, but i didn't add it because i though it would obscure the important parts...

 

btw, shouldn't

 

if(strlen(thingToCopy) >= bufferLength) {

 

be

 

if(strlen(thingToCopy) <= bufferLength) {

 

???

 

I think you made a typo...

Edited by Vortez
0

Share this post


Link to post
Share on other sites

btw, shouldn't

 

if(strlen(thingToCopy) >= bufferLength) {

 

be

 

if(strlen(thingToCopy) <= bufferLength) {

 

???

 

I think you made a typo...

No, (strlen(thingToCopy) >= bufferLength) is correct. It's checking if the length of the string that needs to be copied is longer than the buffer, and if so, returns an error. You can read it as "If the string is longer than the buffer, return -1 to indicate failure."

0

Share this post


Link to post
Share on other sites

Cornstalks is correct.

 

I'd return the number of bytes copied rather than 0 from the function though to indicate success. It will be useful if you are appending strings (don't need to call strlen again).

0

Share this post


Link to post
Share on other sites

Oh lol, my bad, i didn't read the code carefully, im used to do the opposite (check if the string lenght is smaller than buffer size, then return -1 if not, or whatever)

Edited by Vortez
0

Share this post


Link to post
Share on other sites

@musafir2007, do not remove or replace questions, it makes the thread very confusing to follow. You can follow up in a separate reply. If you're making more than a minor edit, it is courtesy to indicate the nature of the edit, or as Vortez did, to use strike through to indicate the old post. But this behaviour is  generally more suitable for replies, where you might otherwise be leaving misleading information, than questions.

 

I have restored a hybrid post from the various questions you appear to have asked.

Edited by rip-off
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0